`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2020/10/17 18:30:30
// Design Name: 
// Module Name: div
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module div(
    input div_clk,
    input resetn,
    input div,
    input div_signed,
    input [31:0] x,
    input [31:0] y,
    output [31:0] s,
    output [31:0] r,
    output complete
    );
    reg [63:0]temp_x;
    reg [63:0]temp_y;
    reg [5:0]count;
    reg complete_r;
    wire [63:0]temp_x_s_1;
    //count caculating times
    always @(posedge div_clk)begin
        if(!resetn) count <= 6'd0;
        else if(count<6'd33 && div) count <= count+1'b1;
        else count <= 6'd0;
    end
    always @(posedge div_clk)begin
        if(!resetn) complete_r <= 61'd0;
        else if (count==6'd32) complete_r <= 1'b1;
        else if (count==6'd33) complete_r <= 1'b0;
    end
    assign complete=complete_r;
    always @(posedge div_clk)begin
        if (!resetn) begin
            temp_x <= 64'h0;
            temp_y <= 64'h0;
        end
        else if (div) begin
            if(count == 6'd0) begin
                if (div_signed) begin
                    temp_x <= (x[31])?{32'h00000000,~x+1'b1}:{32'h00000000,x};
                    temp_y <= (y[31])?{~y+1'b1,32'h00000000}:{y,32'h00000000};
                end
                else begin
                    temp_x <= {32'h00000000,x};
                    temp_y <= {y,32'h00000000};
                end
                
            end
            else begin
                if(temp_x_s_1 >= temp_y) temp_x <= temp_x_s_1 - temp_y + 1'b1;
                else temp_x <= temp_x_s_1;
            end
        end
    end
    assign temp_x_s_1=temp_x << 1;
    assign s = (div_signed & (x[31]^y[31]))? ~temp_x[31:0]+1'b1:temp_x[31:0];
    assign r = (div_signed & x[31])?~temp_x[63:32]+1'b1:temp_x[63:32];
endmodule
